import { createRouter, createWebHistory } from 'vue-router'
import { useStore } from 'vuex'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/LoginSimple.vue'),
      meta: {
        title: '医生登录',
        requiresAuth: false
      }
    },
    {
      path: '/layout',
      name: 'Layout',
      component: () => import('@/components/Layout.vue'),
      redirect: '/scoring/new',
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: '/scoring/new',
          name: 'NewScoring',
          component: () => import('@/views/scoring/NewScoring.vue'),
          meta: {
            title: '开始评分',
            requiresAuth: true
          }
        },
        {
          path: '/scoring/history',
          name: 'ScoringHistory',
          component: () => import('@/views/scoring/History.vue'),
          meta: {
            title: '评分历史',
            requiresAuth: true
          }
        },
        {
          path: '/scoring/detail/:taskId',
          name: 'ScoringDetail',
          component: () => import('@/views/scoring/Detail.vue'),
          meta: {
            title: '评分详情',
            requiresAuth: true
          }
        }
      ]
    },
    {
      path: '/404',
      name: 'NotFound',
      component: () => import('@/views/404.vue'),
      meta: {
        title: '页面不存在',
        requiresAuth: false
      }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const store = useStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 溃疡性结肠炎智能评分系统`
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const isAuthenticated = store.getters['auth/isAuthenticated']

    if (!isAuthenticated) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 不需要认证的页面
    if (to.path === '/login' && store.getters['auth/isAuthenticated']) {
      // 已登录用户访问登录页，跳转到主页
      next('/scoring/new')
    } else {
      next()
    }
  }
})

export default router